package com.xzy.controller.a;

import com.xzy.domain.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

/**
 * 说明：SpringMVC获取请求参数
 *
 * @author xzy
 * @date 2021/11/14 18:31
 */
@Slf4j
@RestController("controllerA")
@RequestMapping("/test_a")
public class TestController {

    /**
     * 通过ServletAPI获取
     */
    @GetMapping("/a1")
    public void testParamA1(HttpServletRequest request) {
        // 如果客户端没有传递相应的参数，获取到的数值为null
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        log.info("username={},password={}", username, password);
    }

    /**
     * 通过ServletAPI获取
     */
    @GetMapping("/a2")
    public void testParamA2(HttpServletRequest request) {
        // 对客户端是否传递参数进行判断
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap.containsKey("username") && parameterMap.containsKey("password")) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            log.info("username={},password={}", username, password);
        }
    }

    /**
     * 通过同名形参获取参数
     */
    @GetMapping("/b1")
    public void testParamB1(String username, String password) {
        log.info("username={},password={}", username, password);
    }

    /**
     * 通过同名形参获取参数
     */
    @GetMapping("/b2")
    public void testParamB2(String[] usernames) {
        log.info("usernames={}", Arrays.toString(usernames));
    }

    /**
     * 通过同名形参获取参数
     */
    @GetMapping("/b3")
    public void testParamB3(String usernames) {
        log.info("usernames={}", usernames);
    }

    /**
     * 通过@RequestParam注解获取参数
     */
    @GetMapping("/c1")
    public void testParamC1(@RequestParam(name = "usn") String username,
                            @RequestParam(name = "pwd") String password,
                            @RequestParam(defaultValue = "m") String sex) {
        log.info("username={},password={},sex={}", username, password, sex);
    }

    /**
     * 通过 POJO 获取参数
     */
    @GetMapping("/d1")
    public void testParamD1(UserDTO userDTO, String username, String password) {
        log.info("username={},password={}", username, password);
        log.info("userDTO={}", userDTO);
    }
}
